<template>
    <div class="app-container">
      <div class="jcxx">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
            <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
          </div>
          <div class="text item">
            <div>
              <el-form ref="PyInbound" :model="pyInboundData" :rules="rules" size="small" label-width="100px"
                label-position="left">
                <el-row type="flex" justify="space-around" align="bottom">
                  <el-col :span="10">
                    <el-form-item label="入库单号" prop="inventoryNumber">
                      <el-input v-model="pyInboundData.inventoryNumber" placeholder="自动获取系统编号" :disabled='true'
                        :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="入库类型" prop="inventoryType">
                      <el-select v-model="pyInboundData.inventoryType" placeholder="请选择入库类型" clearable
                        :style="{ width: '100%' }">
                        <el-option v-for="dict in dict.type.py_instock_type" :key="dict.value" :label="dict.label"
                          :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row type="flex" justify="space-around" align="bottom">
                  <el-col :span="10">
                    <el-form-item label="仓库名称" prop="field102">
                      <el-select v-model="pyInboundData.warehouseId" placeholder="请选择" :style="{ width: '100%' }">
                        <el-option v-for="item in warehouseIds" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="入库日期" prop="inboundDate">
                      <el-date-picker v-model="pyInboundData.inboundDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                        :style="{ width: '100%' }" placeholder="请选择"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row type="flex" justify="space-around" align="bottom">
                  <el-col :span="10">
                    <el-form-item label="关联单号" prop="relatedNumber">
                      <div style="display: flex; align-items: center;">
  
                        <el-input v-model="pyInboundData.relatedNumber" placeholder="请输入" :style="{ width: '100%' }"
                          :disabled="linkPurchaseOrder">
                        </el-input>
                        <el-button style="padding-left: 10px;" v-if="linkPurchaseOrder" @click="openOrderSelection"
                          type="text">查看</el-button>
                        <el-checkbox style="padding-left: 10px;" v-model="linkPurchaseOrder"
                          @change="handleCheckboxChange">关联进货单号</el-checkbox>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="供应商" prop="supplierId">
                      <el-select v-model="pyInboundData.supplierId" placeholder="请选择" :disabled="linkPurchaseOrder"
                        @change="fetchSupplierContact" :style="{ width: '100%' }">
                        <el-option v-for="item in supplierIds" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row type="flex" justify="space-around" align="bottom">
                  <el-col :span="10">
                    <el-form-item label="联系人" prop="contactPerson">
                      <el-input v-model="pyInboundData.contactPerson" placeholder="请输入联系人" :disabled=true
                        :style="{ width: '100%' }">
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="联系方式" prop="contactPhone">
                      <el-input v-model="pyInboundData.contactPhone" placeholder="请输入" :disabled=true
                        :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row style="margin-left: 53px;">
                  <el-col :span="10">
                    <el-form-item label="经办人">
                      <el-cascader v-model="pyInboundData.handler" :options="cascaderOptions" :props="cascaderProps"
                        placeholder="请选择" @change="handleChange" :style="{ width: '100%' }" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row style="margin-left: 60px;">
                  <el-form-item label="备注" prop="remarks">
                    <el-input v-model="pyInboundData.remarks" type="textarea" placeholder="请输入" :maxlength="1000"
                      :autosize="{ minRows: 4, maxRows: 10 }" :style="{ width: '100%' }"></el-input>
                  </el-form-item>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-card>
        <!-- //选择进货 -->
        <el-dialog title="选择进货单" :visible.sync="openPurchaseOrder">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item>
              <el-input v-model="queryParams.phCode" placeholder="请输入进货单号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryParams.phState" placeholder="请选择单据状态" clearable>
                <el-option v-for="dict in dict.type.py_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryParams.supplierId" placeholder="请选择供应商">
                <el-option v-for="item in supplierIds" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-date-picker clearable v-model="queryParams.phDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择进货日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="JHDDhandleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="JHDDresetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table ref="table" v-loading="loading" :data="purchaseList" @selection-change="JHDDhandleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" prop="phId" />
            <el-table-column label="进货单号" align="center" prop="phCode" />
            <el-table-column label="单据状态" align="center" prop="phState">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.py_status" :value="scope.row.phState" />
              </template>
            </el-table-column>
            <el-table-column label="进货日期" align="center" prop="phDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.phDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="供应商" align="center" prop="supplierName" />
            <el-table-column label="进货部门" align="center" prop="deptName" />
            <el-table-column label="进货人" align="center" prop="phPerson" />
            <el-table-column label="货品数量" align="center" prop="goodsNum" />
            <el-table-column label="货品金额" align="center" prop="goodsMoney">
              <template slot-scope="scope">
                {{ fun(scope.row.goodsMoney) }}
              </template>
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="JHDDsubmitForm">确 定</el-button>
            <el-button @click="JHDDcancel">取 消</el-button>
          </div>
  
        </el-dialog>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>入库明细</span>
            <span style="float: right">
              <el-button type="success" @click="RKMXopenDialog">添加</el-button>
              <el-button type="danger">移除</el-button>
            </span>
          </div>
          <!-- //添加入库明细 -->
          <el-dialog title="添加货品" style="width: 100%" :visible.sync="openInventoryDetails">
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple-dark" style="margin-top: -30px;padding-left: 20px;">
                  <!-- <span> 进货单号：{{ inboundOrderNumber }}</span>
                  <span> 进货日期：{{ inboundDate }}</span>
                  <span> 供应商：{{ supplier }}</span>
                  <span> 金额：{{ totalAmount }}</span>
                  <span> 数量：{{ totalQuantity }}</span> -->
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple-dark">
                  <el-form :model="JHMXqueryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
                    <el-form-item>
                      <el-input v-model="JHMXqueryParams.productCode" placeholder="请输入货品编号名称" clearable
                        @keyup.enter.native="handleQuery" />
                    </el-form-item>
  
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="RKMXhandleQuery">搜索</el-button>
                      <el-button icon="el-icon-refresh" size="mini" @click="RKMXresetQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
            <el-table :data="filteredProducts" @selection-change="JHMXhandleSelectionChange" border>
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="phDetailsId" label="序号" width="55"></el-table-column>
  
              <el-table-column prop="productCode" label="货品编号" width="120"></el-table-column>
              <el-table-column prop="productName" label="货品名称" width="120"></el-table-column>
              <el-table-column prop="productModel" label="规格型号" width="120"></el-table-column>
              <el-table-column prop="unit" label="单位" width="90"></el-table-column>
              <el-table-column prop="price" label="进货单价" width="120">
                <template slot-scope="scope">
                  {{ fun(scope.row.price) }}
                </template>
              </el-table-column>
              <el-table-column prop="productNum" label="进货数量" width="120"></el-table-column>
              <el-table-column prop="purchaseAmount" label="进货金额" width="120">
                <template slot-scope="scope">
                  {{ fun(scope.row.purchaseAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="alreadyNum" label="已入库" width="90"></el-table-column>
              <el-table-column prop="notStocked" label="未入库" width="90"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="RKMXsubmitForm">确 定</el-button>
              <el-button @click="openInventoryDetails = false">取 消</el-button>
            </div>
          </el-dialog>
  
          <div class="text item">
  
            <el-table ref="table" :data="RKMXtableData" style="width: 100%" @selection-change="RKMXhandleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column fixed prop="phDetailsId" label="序号" width="50"></el-table-column>
              <el-table-column fixed prop="productName" label="货品名称" width="120"></el-table-column>
              <el-table-column fixed prop="productCode" label="货品编号" width="120"></el-table-column>
              <el-table-column prop="productType" label="货品类型" width="100"></el-table-column>
              <el-table-column prop="productModel" label="规格型号" width="100"></el-table-column>
              <el-table-column prop="unit" label="单位" width="100"></el-table-column>
              <el-table-column prop="currentStock" label="当前库存" width="100"></el-table-column>
              <template v-if="linkPurchaseOrder">
                <el-table-column prop="productNum" label="进货数量" width="100"></el-table-column>
              </template>
              <template v-if="linkPurchaseOrder">
                <el-table-column prop="alreadyNum" label="已入库数量" width="100"></el-table-column>
              </template>
              <template v-if="linkPurchaseOrder">
                <el-table-column prop="notStocked" label="未入库数量" width="100"></el-table-column>
              </template>
              <!-- 库位选择下拉框 -->
              <el-table-column label="入库库位" width="120">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.locationCode" placeholder="请选择"
                    @change="(value) => fetchwhLocationContact(value, scope.row.productCode, scope.row)">
                    <el-option v-for="item in whLocation" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </template>
              </el-table-column>
  
              <!-- 本次入库数量输入框 -->
              <el-table-column label="本次入库数量" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.quantityThisTime" placeholder="请输入数量"
                    @blur="validateQuantity(scope.row)"></el-input>
                </template>
              </el-table-column>
              <template v-if="linkPurchaseOrder"> <el-table-column prop="price" label="进货单价" width="120">
                  <template slot-scope="scope">
                    {{ fun(scope.row.price) }}
                  </template>
                </el-table-column></template>
              <template v-else>
                <el-table-column label="入库单价" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.rkdj" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
              </template>
              <!-- 进货金额 -->
              <template v-if="linkPurchaseOrder"> <el-table-column prop="purchaseAmount" label="进货金额" width="120">
                  <template slot-scope="scope">
                    {{ fun(scope.row.purchaseAmount) }}
                  </template>
                </el-table-column></template>
              <template v-else>
                <el-table-column label="入库金额" width="120">
  
                </el-table-column>
              </template>
              <!-- 批次号输入框 -->
              <el-table-column label="批次号" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.batchNumber" placeholder="请输入批次号"></el-input>
                </template>
              </el-table-column>
  
              <!-- 生产日期日期选择框 -->
              <el-table-column label="生产日期" width="150">
                <template slot-scope="scope">
                  <el-date-picker v-model="scope.row.productionDate" type="date" placeholder="选择日期" style="width: 100%;">
                  </el-date-picker>
                </template>
              </el-table-column>
  
              <!-- 备注输入框 -->
              <el-table-column label="备注" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
                </template>
              </el-table-column>
  
              <el-table-column fixed="right" label="操作" width="120">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="deleteRow(scope.$index, RKMXtableData)" type="text" size="small">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
  
            <tr class="total-row">
              <td>合计</td>
              <span class="you">
                <td>
                  <span class="label">未入库数量:</span>
                  <span class="value">{{ totalCurrentStock }}</span>
                </td>
                <td>
                  <span class="label">已入库数量:</span>
                  <span class="value">{{ totalIncomingQuantity }}</span>
                </td>
                <td>
                  <span class="label">入库种类:</span>
                  <span class="value">{{ totalInStockQuantity }}</span>
                </td>
                <td>
                  <span class="label">入库数量:</span>
                  <span class="value">{{ totalNotStockQuantity }}</span>
                </td>
                <td>
                  <span class="label">入库金额:</span>
                  <span class="value">{{ totalNotStockAmount }}</span>
                </td>
              </span>
  
            </tr>
  
  
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>上传附件</span>
  
          </div>
          <div class="text item">
            <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :on-change="handleChange"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </div>
        </el-card>
        <el-footer class="fixed-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button>关闭</el-button>
          <!-- <el-button>保存并提交</el-button> -->
        </el-footer>
      </div>
    </div>
  </template>
  <script>
  import {
    getCode, selectAllSysDept, selectAllSysDeptByID, selectAllSysUserByParentId,
    selectAllPySuppliers, selectAllBsWarehouse, selectSuppliersByid, selectAllOdPurchaseOrder,
    selectAllOdPurchaseDetails, selectWhInventoryByCode, selectAllBsWhLocation, adddetalis, addInbound
  } from "@/api/inbound/inbound";
  export default {
    dicts: ['py_status', 'py_instock_type'],
    components: {},
    props: [],
    data() {
      return {
  
        // 进货遮罩层
        loading: false,
        gysid: null,
        phCodes: [],
        phsupplierIds: [],//进货单号选中的供应商id
        openPurchaseOrder: false,//选择进货订单弹出框
        //进货订单查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          phCode: null,
          phState: null,
          phDate: null,
  
          supplierId: null // 初始化为对象，即使它的属性为 null  
  
        },
        JHMXqueryParams: {
          productCode: null
        },
        // 进货订单表格数据
        purchaseList: [
          { supplierId: null }
  
        ],
        openInventoryDetails: false,//添加入库明细弹出框
        warehouseIds: [],//仓库名称id数组
        supplierIds: [],//供应商id数组
        whLocation: [],//库位下拉
        tableKey: 0, // 用于强制刷新表格的 key  
        cascaderOptions: [],
        cascaderProps: {
          value: 'value',
          label: 'label',
          children: 'children',
        },
        fileList: [],
        linkPurchaseOrder: true,
  
  
        pyInboundData: {
          inventoryNumber: undefined,
          inventoryType: undefined,//入库类型
          warehouseId: undefined,//仓库名称id
          inboundDate: undefined,
          relatedNumber: undefined,
          supplierId: undefined,
          contactPerson: undefined,
          contactPhone: '',
          remarks: undefined,
          handler: [],
          number: undefined,
          codeId: undefined
        },
        //入库明细表格
        filteredProducts: [
  
        ],
        selectedProducts: [],// 假设选中的数据  
        RKMXtableData: [],
        rules: {
          // inventoryNumber: [
          //   { required: true, message: '请输入入库单号', trigger: 'blur' }
          // ],
          // inventoryType: [
          //   { required: true, message: '请选择入库类型', trigger: 'change' }
          // ],
          // warehouseId: [
          //   { required: true, message: '请选择仓库名称', trigger: 'change' }
          // ],
          // inboundDate: [
          //   { required: true, message: '请选择入库日期', trigger: 'change' }
          // ],
          // relatedNumber: [
          //   { required: true, message: '请输入关联单号', trigger: 'blur' }
          // ],
          // supplierId: [
          //   { required: true, message: '请选择供应商', trigger: 'change' }
          // ],
          // contactPerson: [
          //   { required: true, message: '请输入联系人', trigger: 'blur' }
          // ],
          // contactNumber: [
          //   { required: true, message: '请输入联系方式', trigger: 'blur' }
          // ],
          // handler: [
          //   { required: true, message: '请选择经办人', trigger: 'change' }
          // ]
        }
      }
    },
    computed: {
      totalCurrentStock() {
        return '11'
      },
      totalIncomingQuantity() {
        return '11'
      },
      totalInStockQuantity() {
        return '11'
      },
      totalNotStockQuantity() {
        return '11'
      },
      totalNotStockAmount() {
        return '11'
      }
    },
    created() {
      // 确保selectAllBsWarehouse是一个函数并调用它
      selectAllBsWarehouse().then(response => {
        this.warehouseIds = response.data.map(item => ({
          value: item.warehouseId,
          label: item.warehouseName
        }));
      }).catch(error => {
        console.error('Fetching warehouses failed:', error);
      });
  
      selectAllPySuppliers()
        .then(response => {
          this.supplierIds = response.data.map(item => ({
            value: item.supplierId,
            label: item.supplierName
          }));
        }).catch(error => {
          console.error('Fetching suppliers failed:', error);
        });
      selectAllBsWhLocation()
        .then(response => {
          this.whLocation = response.data.map(item => ({
            value: item.locationCode,
            label: item.locationName
          }));
        }).catch(error => {
          console.error('selectAllBsWhLocation:', error);
        });
  
      this.fetchItems();
      getCode(2).then(response => {
  
        this.pyInboundData.inventoryNumber = response.sequence;
        this.pyInboundData.number = response.number;
        this.pyInboundData.codeId = response.codeId;
      });
    },
    methods: {
      //金额保留2位数
      fun(val) {
        return Number(val).toFixed(2);
      },
      //选中供应商自动获取联系人和电话
      fetchSupplierContact(selectedSupplierId) {
        selectSuppliersByid(selectedSupplierId)
          .then(response => {
            // 更新联系人的电话
            this.pyInboundData.contactPerson = response.data.contactPerson || ''; // 确保是字符串
            this.pyInboundData.contactPhone = response.data.contactPhone || ''; // 确保是字符串
          })
          .catch(error => {
            console.error('获取联系人信息失败:', error);
          });
      },
      //保存
      submitForm() {
        this.$refs.PyInbound.validate((valid) => {
          if (valid) {
            // 表单验证通过，处理表单提交
            console.log('表单验证通过，提交数据:', this.pyInboundData);
            console.log('表单验证通过，提交数据2:', this.RKMXtableData);
            addInbound(this.pyInboundData).then(response => {
              console.log('新增后端响应:', JSON.stringify(response, null, 2));
              this.$modal.msgSuccess("新增成功");
              // this.open = false;
              // this.getList();
            });
            adddetalis(this.RKMXtableData).then(response => {
              console.log('新增后端响应:', JSON.stringify(response, null, 2));
              this.$modal.msgSuccess("新增成功");
              // this.open = false;
              // this.getList();
            });
            // 这里可以调用 API 提交表单数据
          } else {
            // 表单验证失败，提示用户
            console.log('表单验证失败，请检查输入');
            return false;
          }
        });
        for (let row of this.RKMXtableData) {
          if (!row.locationCode) {
            this.$message.error('请选择入库库位！');
            return;
          }
          if (!row.quantityThisTime) {
            this.$message.error('本次入库数量不能为空！');
            return;
          }
          if (!row.batchNumber) {
            this.$message.error('批次号不能为空！');
            return;
          }
          if (!row.productionDate) {
            this.$message.error('生产日期不能为空！');
            return;
          }
          // 其他需要验证的字段...  
        }
      },
  
      async fetchItems() {
        try {
          const response = await selectAllSysDept();
          if (Array.isArray(response)) {
            this.cascaderOptions = await this.convertToCascaderOptions(response);
          } else {
            console.error('Expected an array, but got:', response);
          }
        } catch (error) {
          console.error('Error fetching items:', error);
        }
      },
      async convertToCascaderOptions(data) {
        if (!Array.isArray(data)) {
          console.error('Expected an array, but got:', data);
          return [];
        }
  
        // 创建一个映射，用于快速查找父项
        const itemMap = new Map(data.map(item => [item.deptId, item]));
        // 创建一个数组，用于存储顶级项
        const topLevelItems = [];
        data.forEach(async (item) => {
          if (item.parentId === 0) {
            // 顶级项直接添加到 topLevelItems
            topLevelItems.push(await this.createOption(item));
          } else {
            // 非顶级项，尝试找到其父项并添加到 children 数组
            const parentItem = itemMap.get(item.parentId);
            if (parentItem) {
              const childItem = await this.createOption(item);
              if (parentItem.children) {
                parentItem.children.push(childItem);
              } else {
                parentItem.children = [childItem];
              }
            }
          }
        });
  
        return topLevelItems;
      },
      async createOption(item) {
        return {
          value: item.deptId,
          label: item.deptName,
          children: await this.fetchChildren(item.deptId),
          users: await this.fetchUsers(item.deptId) // 获取该部门的用户
        };
      },
      async fetchUsers(deptId) {
        try {
          const response = await selectAllSysUserByParentId(deptId); // 假设你有这个 API
          if (Array.isArray(response)) {
            return response.map(user => ({
              value: user.userId, // 假设用户对象有 userId
              label: user.userName // 假设用户对象有 userName
            }));
          } else {
            console.error('Expected an array, but got:', response);
            return [];
          }
        } catch (error) {
          console.error('Error fetching users:', error);
          return [];
        }
      },
      async fetchChildren(parentId) {
        try {
          const response = await selectAllSysDeptByID(parentId);
          if (Array.isArray(response)) {
            return Promise.all(response.map(async (item) => {
              const users = await this.fetchUsers(item.deptId);
              const children = await this.fetchChildren(item.deptId); // 递归获取子部门
              return {
                value: item.deptId,
                label: item.deptName,
                children: [
                  ...children,
                  ...users.map(user => ({
                    value: user.value,   // 使用用户的ID
                    label: user.label, // 用户的显示名称
                    isUser: true // 标识这是用户信息
                  }))
                ]
              };
            }));
          } else {
            console.error('Expected an array, but got:', response);
            return [];
          }
        } catch (error) {
          console.error('Error fetching children:', error);
          return [];
        }
      },
      handleChange(value) {
        // 获取选中的最后一个子级的值，即用户ID
        const currentSelectedValue = value[value.length - 1];
        // 更新 pyInboundData.handler 为当前选择的用户ID
        this.pyInboundData.handler = currentSelectedValue;
      },
      JHDDgetList() {
        selectAllOdPurchaseOrder(this.queryParams)
          .then(response => {
            // // 使用 JSON.stringify 转换并美化输出
            // console.log('后端响应:', JSON.stringify(response, null, 2));
  
            // 假设 response.data 是一个数组，包含多个进货单信息
            this.purchaseList = response.data.map(item => ({
              phId: item.phId,
              phCode: item.phCode,
              phState: item.phState,
              phDate: item.phDate,
              supplierName: item.pySuppliers ? item.pySuppliers.supplierName : '', // 供应商名称
              supplierId: item.pySuppliers ? item.pySuppliers.supplierId : '',
              deptName: item.sysDept ? item.sysDept.deptName : '', // 进货部门名称
              phPerson: item.phPerson, // 进货人
              goodsNum: item.goodsNum, // 货品数量
              goodsMoney: item.goodsMoney // 货品金额
            }));
  
            // 如果需要进一步处理 response 数据，可以在这里添加
            // 例如：
            // this.total = response.total; // 总记录数
          })
          .catch(error => {
            console.error('请求失败:', error);
          });
      },
      openOrderSelection() {
        this.openPurchaseOrder = true
        this.JHDDgetList();
      },
      //进货订单搜索
      JHDDhandleQuery() {
        // console.log("阿三大苏打城市达成:"+JSON.stringify(this.queryParams, null, 2))
        this.JHDDgetList();
        // this.queryParams.pageNum = 1;
      },
      //进货订单重置
      JHDDresetQuery() {
        this.queryParams.phCode = '';
        this.queryParams.phState = null;
        this.queryParams.supplierId = null;
        this.queryParams.phDate = null;
      },
      //进货订单确定
      JHDDsubmitForm() {
        // 检查是否选择了供应商  
        if (!this.phsupplierIds.length) {
          this.pyInboundData.supplierId = []; // 将供应商ID设置为空数组  
          return; // 直接返回，不执行后面的代码  
        }
  
        // 此时确认至少有一个供应商选择  
        this.pyInboundData.relatedNumber = this.phCodes.join(''); // 设置相关编号  
        this.pyInboundData.supplierId = this.phsupplierIds[0]; // 设置有效的ID  
  
        // 继续调用获取供应商联系信息  
        this.fetchSupplierContact(this.pyInboundData.supplierId);
  
        // 关闭采购订单窗口  
        this.openPurchaseOrder = false;
      },
      JHDDhandleSelectionChange(selection) {
  
        if (selection.length > 1) {
          // 如果选择超过一项，取消之前的选择
          this.$refs.table.clearSelection();
          this.$refs.table.toggleRowSelection(selection[selection.length - 1], true);
          selection = [selection[selection.length - 1]];
        } else if (selection.length === 0) {
          this.phCodes = []
          this.phsupplierIds = []
        }
        this.phCodes = selection.map(item => item.phCode);
        this.phsupplierIds = selection.map(item => item.supplierId);
        console.log("选中:", selection);
  
      },
      //取消
      JHDDcancel() {
        this.pyInboundData.relatedNumber = null; // 设置相关编号  
        this.pyInboundData.supplierId = null; // 设置有效的ID  
        this.pyInboundData.contactPerson = null;
        this.pyInboundData.contactPhone = null; // 设置有效的ID   
        this.openPurchaseOrder = false;
      },
      //关联进货单号
      handleCheckboxChange() {
  
      },
      //入库明细添加按钮
      RKMXopenDialog() {
        this.openInventoryDetails = true
        const query = {
          phCodes: this.phCodes.join(','),
          productCode: this.JHMXqueryParams.productCode
        };
        console.log("进货订单:" + this.phCodes)
        selectAllOdPurchaseDetails(query)
          .then(response => {
            console.log("萨达安安:" + JSON.stringify(response.data, null, 2))
            this.filteredProducts = response.data
          })
          .catch(error => {
            console.error('获取联系人信息失败:', error);
          });
      },
      //入库明细搜索
      RKMXhandleQuery() {
        console.log("萨达安安:" + JSON.stringify(this.JHMXqueryParams, null, 2))
  
        selectAllOdPurchaseDetails(this.JHMXqueryParams)
          .then(response => {
            // console.log("萨达安安:" + JSON.stringify(response.data, null, 2))
            this.filteredProducts = response.data
          })
          .catch(error => {
            console.error('获取联系人信息失败:', error);
          });
      },
      JHMXhandleSelectionChange(selection) {
        console.log("选:", selection);
        this.selectedProducts = selection
      },
      RKMXresetQuery() {
  
      },
      RKMXsubmitForm() {
        this.RKMXtableData = this.selectedProducts
        console.log("过滤后的产品:", this.RKMXtableData);
        this.openInventoryDetails = false;
  
      },
      //入库明细最终表格
      deleteRow(index, rows) {
        rows.splice(index, 1);
      },
      // 多选框选中数据
      RKMXhandleSelectionChange(selection) {
        console.log("选中:" + JSON.stringify(selection, null, 2))
        // // this.ids = selection.map(item => item.inventoryId)
        // // this.single = selection.length !== 1
        // // this.multiple = !selection.length
      },
      fetchwhLocationContact(selectedLocation, productCode, currentRow) {
        // console.log("选中的库位:", selectedLocation);
        // console.log("货品编号:", productCode); // 访问当前行的货品编号  
  
        const query = {
          location: selectedLocation,
          productCode: productCode
        };
  
        // 调用 API 查询库存  
        selectWhInventoryByCode(query)
          .then(response => {
            console.log("库存:" + JSON.stringify(response.data, null, 2));
  
            // 假设 response.data 是一个数组，我们只关心第一个元素  
            if (response.data.length > 0) {
              const inventoryData = response.data[0];
              // 直接更新当前行的 currentStock  
              this.$set(currentRow, 'currentStock', inventoryData.currentInventory); // 更新当前行的 currentStock  
              console.log("更新后的当前库存:", currentRow.currentStock); // 打印更新后的库存  
            } else {
              console.log("没有找到库存数据");
              // 如果没有找到，可以考虑将 currentStock 设置为空或者提示用户  
              this.$set(currentRow, 'currentStock', 0); // 更新当前行的 currentStock  
            }
          })
          .catch(error => {
            console.error('查询库存失败:', error);
          });
      },
      validateQuantity(row) {
        const enteredQuantity = Number(row.quantityThisTime);
        const notStockedQuantity = Number(row.notStocked);
  
        if (enteredQuantity > notStockedQuantity) {
          this.$message.error('不允许大于未入库数量！');
          row.quantityThisTime = notStockedQuantity; // 可选：将输入框的值重置为未入库数量  
        }
      },
  
  
    },
  
  }
  </script>
  <style>
  .fixed-footer {
    position: fixed;
    bottom: 0;
    left: 100px;
  
    right: 0;
    padding-left: 1400px;
    padding-top: 20px;
    background-color: #f4f4f4;
    /* 设置底部背景色 */
    z-index: 1000;
    /* 确保底部不被遮挡 */
  }
  
  .jcxx {
    margin-top: 20px;
  
  }
  
  .text {
    font-size: 14px;
  }
  
  .item {
    margin-bottom: 18px;
  }
  
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  
  .clearfix:after {
    clear: both
  }
  
  .box-card {
    width: 100%;
    margin-top: 20px;
  }
  
  .total-row {
    background-color: #f9f9f9;
    /* 背景色 */
    font-weight: bold;
    /* 粗体 */
  }
  
  .label {
    color: black;
    /* 标签字体颜色 */
    margin-left: 10px;
  }
  
  .you {
    margin-left: 930px;
  }
  
  .value {
    color: rgb(227, 139, 50);
    /* 数字字体颜色 */
  }
  
  /* 如果需要调整对齐方式，可以添加其他样式 */
  .total-row td {
    text-align: left;
    /* 左对齐 */
  }
  
  .total-row td:last-child {
    text-align: right;
    /* 最后一列右对齐 */
  }
  </style>
  